<?php
namespace app\api\controller;

use app\api\model\User;
use app\api\model\SendVerify;
use app\api\validate\UserRegisterValidate;
use app\api\validate\UserLoginValidate;
use app\api\validate\SendVerifyValidate;
use think\exception\ValidateException;
use app\BaseController;


class UserController extends BaseController
{


    // 发送短信验证码
    public function sendVerify(SendVerify $sendVerify)
    {

        try {
            $data = $this->request->param();
            validate(SendVerifyValidate::class)->check($data);
            
            $verifyCode = rand(1000,9999);
            $return = $sendVerify->send($data['mobile'],$verifyCode);
            return $this->returnJson('ok',$return);
            
        } catch (ValidateException $e) {
            return $this->returnJson($e->getError());
        }
    }
    
    public function login(User $user)
    {
        try {
            $data = $this->request->param();
            validate(UserLoginValidate::class)->check($data);

            $data = $user->where('mobile',$data['mobile'])->where('password',md5($data['password']))->find();
            if(empty($data)){
                return $this->returnJson('账号或者密码错误|9');
            }
            return $this->returnJson('ok',$data);
        } catch (ValidateException $e) {
            $message = explode('|',$e->getError());
            return $this->returnJson($e->getError());
        }
    }

    public function register(User $user)
    {
        try {
            $data = $this->request->param();
            validate(UserRegisterValidate::class)->check($data);
            $result = $user->register($data['mobile'],$data['password']);
            if($result == FALSE){
                return $this->returnJson($user->getError());
            }
            return $this->returnJson('ok',$result);
        } catch (ValidateException $e) {
            return $this->returnJson($e->getError());
        }
    }
}
